<template>
  <div class="global-search">
    <div class="container">
      <!-- 搜索筛选栏 -->
      <div class="search-filters card">
        <div class="filter-row">
          <div class="filter-group">
            <label>品牌：</label>
            <select v-model="filters.brand" class="select">
              <option value="">全部</option>
              <option v-for="brand in brands" :key="brand.id" :value="brand.name">
                {{ brand.name }}
              </option>
            </select>
          </div>

          <div class="filter-group">
            <label>季次：</label>
            <select v-model="filters.season" class="select">
              <option value="">全部</option>
              <option v-for="season in seasons" :key="season.id" :value="season.name">
                {{ season.name }}
              </option>
            </select>
          </div>

          <div class="filter-group">
            <label>状态：</label>
            <select v-model="filters.status" class="select">
              <option value="">全部</option>
              <option v-for="option in statusOptions" :key="option.value" :value="option.value">
                {{ option.label }}
              </option>
            </select>
          </div>
        </div>

        <div class="filter-row">
          <div class="filter-group">
            <label>款式ID：</label>
            <input type="text" placeholder="输入款式ID" class="input" v-model="filters.styleId" />
          </div>

          <div class="filter-group">
            <label>颜色ID：</label>
            <input type="text" placeholder="输入颜色ID" class="input" v-model="filters.colorId" />
          </div>

          <div class="filter-group">
            <label>关键字：</label>
            <input type="text" placeholder="名称/标签" class="input" v-model="filters.keyword" />
          </div>

          <button class="btn btn-primary">查询</button>
        </div>
      </div>

      <!-- 搜索结果 -->
      <div class="search-results">
        <div class="results-header card">
          <div class="results-info">
            <span>找到 {{ filteredResults.length }} 条结果</span>
          </div>
          <div class="results-actions">
            <button class="btn">
              <ExportIcon :size="14" />
              导出
            </button>
            <button class="btn">批量降级为匹配失败</button>
            <button class="btn">批量套用模板</button>
          </div>
        </div>

        <div class="results-table card">
          <table class="table">
            <thead>
              <tr>
                <th>品牌</th>
                <th>季次</th>
                <th>款式ID</th>
                <th>颜色ID</th>
                <th>状态</th>
                <th>更新时间</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr
                v-for="result in filteredResults"
                :key="`${result.brand}-${result.season}-${result.styleId}-${result.colorId}`"
              >
                <td>{{ result.brand }}</td>
                <td>{{ result.season }}</td>
                <td>{{ result.styleId }}</td>
                <td>{{ result.colorId }}</td>
                <td>
                  <span class="badge" :class="getStatusBadgeClass(result.status)">
                    {{ getStatusText(result.status) }}
                  </span>
                </td>
                <td>{{ result.updateTime }}</td>
                <td>
                  <div class="action-buttons">
                    <button class="btn">查看</button>
                    <button class="btn">编辑</button>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { getBrands, getSeasons } from '../api/batchApi'
import { getStatusOptions } from '../api/colorApi'
import { globalSearch } from '../api/searchApi'
import { ExportIcon } from '../components/icons'

export default {
  name: 'GlobalSearch',
  components: {
    ExportIcon,
  },
  setup() {
    const filters = ref({
      brand: '',
      season: '',
      status: '',
      styleId: '',
      colorId: '',
      keyword: '',
    })

    // 数据状态
    const brands = ref([])
    const seasons = ref([])
    const statusOptions = ref([])
    const searchResults = ref([])
    const loading = ref(false)

    // 加载数据
    const loadData = async () => {
      loading.value = true
      try {
        const [brandsData, seasonsData, statusOptionsData] = await Promise.all([
          getBrands(),
          getSeasons(),
          getStatusOptions(),
        ])
        brands.value = brandsData
        seasons.value = seasonsData
        statusOptions.value = statusOptionsData
      } catch (error) {
        console.error('加载数据失败:', error)
      } finally {
        loading.value = false
      }
    }

    // 执行搜索
    const performSearch = async () => {
      loading.value = true
      try {
        const results = await globalSearch({
          keyword: filters.value.keyword,
          brand: filters.value.brand,
          season: filters.value.season,
          status: filters.value.status,
        })
        searchResults.value = results
      } catch (error) {
        console.error('搜索失败:', error)
      } finally {
        loading.value = false
      }
    }

    const filteredResults = computed(() => {
      return searchResults.value.filter(result => {
        if (filters.value.brand && result.brand !== filters.value.brand) return false
        if (filters.value.season && result.season !== filters.value.season) return false
        if (filters.value.status && result.status !== filters.value.status) return false
        if (filters.value.styleId && !result.styleId.includes(filters.value.styleId)) return false
        if (filters.value.colorId && !result.colorId.includes(filters.value.colorId)) return false
        if (filters.value.keyword) {
          const keyword = filters.value.keyword.toLowerCase()
          if (
            !result.styleId.toLowerCase().includes(keyword) &&
            !result.colorId.toLowerCase().includes(keyword)
          ) {
            return false
          }
        }
        return true
      })
    })

    const getStatusText = status => {
      const statusMap = {
        pending: '待匹配',
        success: '匹配成功',
        failed: '匹配失败',
        empty: '放弃',
        vectoring: '向量中',
        completed: '完成',
      }
      return statusMap[status] || status
    }

    const getStatusBadgeClass = status => {
      const classMap = {
        pending: 'badge-pending',
        success: 'badge-success',
        failed: 'badge-error',
        empty: 'badge-warning',
        vectoring: 'badge-warning',
        completed: 'badge-success',
      }
      return classMap[status] || 'badge-pending'
    }

    // 组件挂载时加载数据
    onMounted(() => {
      loadData()
    })

    return {
      filters,
      brands,
      seasons,
      statusOptions,
      filteredResults,
      loading,
      performSearch,
      getStatusText,
      getStatusBadgeClass,
    }
  },
}
</script>

<style scoped>
.search-filters {
  margin-bottom: 20px;
}

.filter-row {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
  margin-bottom: 16px;
}

.filter-row:last-child {
  margin-bottom: 0;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-group label {
  font-size: 13px;
  color: var(--text-secondary);
  white-space: nowrap;
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.results-info {
  font-size: 14px;
  color: var(--text-secondary);
}

.results-actions {
  display: flex;
  gap: 8px;
}

.table {
  width: 100%;
  border-collapse: collapse;
}

.table th,
.table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid var(--border-color);
}

.table th {
  background: #fafafa;
  font-weight: 600;
  color: var(--text-color);
}

.action-buttons {
  display: flex;
  gap: 6px;
}

.action-buttons .btn {
  font-size: 12px;
  padding: 4px 8px;
}

@media (max-width: 768px) {
  .filter-row {
    flex-direction: column;
    gap: 12px;
  }

  .results-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .results-actions {
    flex-direction: column;
  }
}
</style>
